<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>回收站管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css">
    <script type="text/javascript" th:src="@{'https://api.map.baidu.com/api?v=3.0&ak=' + ${@baiduMapConfig.apiKey}}"></script>
    <style>
        .station-card {
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        .station-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .status-badge {
            position: absolute;
            top: 10px;
            right: 10px;
        }
        #map-container {
            width: 100%;
            height: 400px;
            margin-bottom: 1rem;
        }
        .map-search-box {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 1000;
            background: white;
            padding: 10px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>回收站管理</h2>
            <button class="btn btn-primary" onclick="openStationModal()">
                <i class="fas fa-plus"></i> 添加回收站
            </button>
        </div>

        <!-- 搜索表单 -->
        <div class="card mb-4">
            <div class="card-body">
                <form id="searchForm" class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" name="name" placeholder="回收站名称">
                    </div>
                    <div class="col-md-3">
                        <input type="text" class="form-control" name="address" placeholder="回收站地址">
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" name="status">
                            <option value="">全部状态</option>
                            <option value="1">营业中</option>
                            <option value="0">已关闭</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <button type="submit" class="btn btn-primary me-2">搜索</button>
                        <button type="button" class="btn btn-secondary" onclick="resetSearch()">重置</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 回收站列表 -->
        <div class="row" id="stationList">
            <div th:each="station : ${stations}" class="col-md-6 col-lg-4">
                <div class="card station-card">
                    <div class="card-body">
                        <span th:class="${station.status == 1 ? 'badge bg-success' : 'badge bg-danger'} + ' status-badge'"
                              th:text="${station.status == 1 ? '营业中' : '已关闭'}">
                        </span>
                        <h5 class="card-title" th:text="${station.name}">回收站名称</h5>
                        <p class="card-text">
                            <i class="fas fa-map-marker-alt"></i>
                            <span th:text="${station.address}">回收站地址</span>
                        </p>
                        <p class="card-text">
                            <i class="fas fa-phone"></i>
                            <span th:text="${station.contactPhone}">联系电话</span>
                        </p>
                        <p class="card-text">
                            <i class="fas fa-clock"></i>
                            <span th:text="${station.businessHours}">营业时间</span>
                        </p>
                        <p class="card-text">
                            <i class="fas fa-recycle"></i>
                            <span th:text="${station.acceptableItems}">可回收物品</span>
                        </p>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-primary me-2" th:onclick="'editStation(' + ${station.id} + ')'">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button class="btn btn-sm btn-danger me-2" th:onclick="'deleteStation(' + ${station.id} + ')'">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                            <button th:class="${station.status == 1 ? 'btn btn-sm btn-warning' : 'btn btn-sm btn-success'}"
                                    th:onclick="'toggleStatus(' + ${station.id} + ',' + ${station.status} + ')'">
                                <i class="fas fa-power-off"></i>
                                <span th:text="${station.status == 1 ? '关闭' : '开启'}"></span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑回收站模态框 -->
    <div class="modal fade" id="stationModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">添加回收站</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="stationForm">
                        <input type="hidden" id="stationId">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">回收站名称</label>
                                    <input type="text" class="form-control" id="name" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">回收站地址</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="address" required>
                                        <button class="btn btn-outline-secondary" type="button" onclick="searchAddress()">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col">
                                        <label class="form-label">纬度</label>
                                        <input type="number" class="form-control" id="latitude" required step="any">
                                    </div>
                                    <div class="col">
                                        <label class="form-label">经度</label>
                                        <input type="number" class="form-control" id="longitude" required step="any">
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">联系电话</label>
                                    <input type="tel" class="form-control" id="contactPhone" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">营业时间</label>
                                    <input type="text" class="form-control" id="businessHours" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">可回收物品</label>
                                    <textarea class="form-control" id="acceptableItems" rows="3"></textarea>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">在地图上选择位置</label>
                                    <div id="map-container"></div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveStation()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        let stationModal;
        let map;
        let marker;
        let geolocation;
        
        document.addEventListener('DOMContentLoaded', function() {
            stationModal = new bootstrap.Modal(document.getElementById('stationModal'));
            initMap();
        });

        function initMap() {
            // 创建地图实例
            map = new BMap.Map("map-container");
            // 创建点坐标（默认北京市中心）
            const point = new BMap.Point(116.404, 39.915);
            // 初始化地图，设置中心点坐标和地图级别
            map.centerAndZoom(point, 12);
            // 开启鼠标滚轮缩放
            map.enableScrollWheelZoom();
            // 添加地图控件
            map.addControl(new BMap.NavigationControl());
            map.addControl(new BMap.ScaleControl());
            
            // 点击地图更新标记和经纬度
            map.addEventListener("click", function(e) {
                updateMarker(e.point);
                updateLatLng(e.point.lat, e.point.lng);
            });
        }

        function updateMarker(point) {
            // 清除旧标记
            map.clearOverlays();
            // 创建新标记
            marker = new BMap.Marker(point);
            map.addOverlay(marker);
            // 获取地址信息
            const geocoder = new BMap.Geocoder();
            geocoder.getLocation(point, function(result) {
                if (result) {
                    document.getElementById('address').value = result.address;
                }
            });
        }

        function updateLatLng(lat, lng) {
            document.getElementById('latitude').value = lat;
            document.getElementById('longitude').value = lng;
        }

        function searchAddress() {
            const address = document.getElementById('address').value;
            if (!address) {
                Swal.fire({
                    icon: 'warning',
                    title: '请输入地址',
                    text: '请先输入要搜索的地址'
                });
                return;
            }

            const localSearch = new BMap.LocalSearch(map);
            localSearch.setSearchCompleteCallback(function(searchResult) {
                if (searchResult && searchResult.getPoi(0)) {
                    const poi = searchResult.getPoi(0);
                    const point = poi.point;
                    map.centerAndZoom(point, 16);
                    updateMarker(point);
                    updateLatLng(point.lat, point.lng);
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '地址搜索失败',
                        text: '未找到该地址，请尝试其他地址'
                    });
                }
            });
            localSearch.search(address);
        }

        function openStationModal() {
            document.getElementById('modalTitle').textContent = '添加回收站';
            document.getElementById('stationForm').reset();
            document.getElementById('stationId').value = '';
            // 重置地图视图
            const point = new BMap.Point(116.404, 39.915);
            map.centerAndZoom(point, 12);
            map.clearOverlays();
            stationModal.show();
        }

        function editStation(id) {
            document.getElementById('modalTitle').textContent = '编辑回收站';
            fetch(`/admin/stations/${id}`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('stationId').value = data.id;
                    document.getElementById('name').value = data.name;
                    document.getElementById('address').value = data.address;
                    document.getElementById('latitude').value = data.latitude;
                    document.getElementById('longitude').value = data.longitude;
                    document.getElementById('contactPhone').value = data.contactPhone;
                    document.getElementById('businessHours').value = data.businessHours;
                    document.getElementById('acceptableItems').value = data.acceptableItems;
                    
                    // 更新地图标记
                    const point = new BMap.Point(data.longitude, data.latitude);
                    map.centerAndZoom(point, 16);
                    updateMarker(point);
                    
                    stationModal.show();
                });
        }

        function saveStation() {
            const formData = {
                id: document.getElementById('stationId').value,
                name: document.getElementById('name').value,
                address: document.getElementById('address').value,
                latitude: parseFloat(document.getElementById('latitude').value),
                longitude: parseFloat(document.getElementById('longitude').value),
                contactPhone: document.getElementById('contactPhone').value,
                businessHours: document.getElementById('businessHours').value,
                acceptableItems: document.getElementById('acceptableItems').value
            };

            const url = formData.id ? `/admin/stations/${formData.id}` : '/admin/stations';
            const method = formData.id ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                stationModal.hide();
                Swal.fire({
                    icon: 'success',
                    title: '保存成功',
                    showConfirmButton: false,
                    timer: 1500
                }).then(() => {
                    window.location.reload();
                });
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: '保存失败',
                    text: error.message
                });
            });
        }

        function deleteStation(id) {
            Swal.fire({
                title: '确认删除',
                text: '确定要删除这个回收站吗？',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch(`/admin/stations/${id}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data) {
                            Swal.fire({
                                icon: 'success',
                                title: '删除成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                window.location.reload();
                            });
                        }
                    });
                }
            });
        }

        function toggleStatus(id, currentStatus) {
            const newStatus = currentStatus === 1 ? 0 : 1;
            fetch(`/admin/stations/${id}/status`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ status: newStatus })
            })
            .then(response => response.json())
            .then(data => {
                if (data) {
                    window.location.reload();
                }
            });
        }

        function resetSearch() {
            document.getElementById('searchForm').reset();
            document.getElementById('searchForm').submit();
        }

        document.getElementById('searchForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const params = new URLSearchParams();
            for (let pair of formData.entries()) {
                if (pair[1]) {
                    params.append(pair[0], pair[1]);
                }
            }
            window.location.href = '/admin/stations?' + params.toString();
        });
    </script>
</body>
</html> 